package com.glory.brepda.activity.lanjian;

import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.LotAndPackagingfileEntity;
import com.glory.brepda.entity.WoPartWobomline;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class BreYFCWaferHDActivity extends BaseActivity {

    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.etCust)
    FreeUI_ClearEditText etCust;
    @BindView(R.id.etMMT)
    FreeUI_ClearEditText etMMT;
    @BindView(R.id.etproductModuct)
    FreeUI_ClearEditText etproductModuct;
    @BindView(R.id.etWaferId)
    FreeUI_ClearEditText etWaferId;
    @BindView(R.id.etWaferLot)
    FreeUI_ClearEditText etWaferLot;
    @BindView(R.id.etWaferhd)
    FreeUI_ClearEditText etWaferhd;
    @BindView(R.id.etBeiZu)
    FreeUI_ClearEditText etBeiZu;
    @BindView(R.id.isPass)
    LinearLayout isPass;
    @BindView(R.id.layoutCust)
    LinearLayout layoutCust;
    @BindView(R.id.layoutMmt)
    LinearLayout layoutMmt;
    @BindView(R.id.layoutProduct)
    LinearLayout layoutProduct;
    @BindView(R.id.ethyh)
    TextView ethyh;
    @BindView(R.id.ivBCOPArrow)
    ImageView ivBCOPArrow;
    @BindView(R.id.flBCOPList)
    FrameLayout flBCOPList;

    @BindView(R.id.tvPassype)
    TextView tvPassype;
    @BindView(R.id.ivPassArrow)
    ImageView ivPassArrow;
    @BindView(R.id.flPassList)
    FrameLayout flPassList;

    @BindView(R.id.tvYaoqiuType)
    TextView tvYaoqiuType;
    @BindView(R.id.ivYaoqiuArrow)
    ImageView ivYaoqiuArrow;
    @BindView(R.id.flYaoqiuList)
    FrameLayout flYaoqiuList;

    private WoPartWobomline woPartWobomline;
    private FreeUI_GeneralPop codePopHyh,code1,code2;

    List<String> hyhList = new ArrayList<>();
    List<String> allhyhList = new ArrayList<>();
    List<String> haveDatahyhList = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_bre_yfcwafer_hdactivity;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        isPass.setVisibility(View.GONE);
        layoutCust.setVisibility(View.GONE);
        layoutMmt.setVisibility(View.GONE);
        layoutProduct.setVisibility(View.GONE);

        initEdit(etEqpId, sa -> {
            //获取工单，产品，工单BomLine信息
            FreeUI_EntityCallBack<BaseResponseBean<WoPartWobomline>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<WoPartWobomline>>
                    (new TypeToken<BaseResponseBean<WoPartWobomline>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<WoPartWobomline>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        hyhList.clear();
                        allhyhList.clear();
                        haveDatahyhList.clear();
                        ethyh.setText(null);
                        woPartWobomline = response.body().getResponse().getBody();
                        initInfoView(woPartWobomline);
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<WoPartWobomline>> response) {
                    super.onError(response);
                    loadError(response.getException(), "失败");
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("WORDER", getText(etEqpId));
            map.addProperty("ACTION", "WORDER_QUERY");
            NetUtils.requestPostNet("IF.WORDER_QUERY_INFOS", "Common", getApplication(), map, callBack);
        });

        // ①组件监听的方式
        flPassList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (code1 != null) {
                    if (code1.isShowing()) {
                        code1.dismiss();
                    }
                } else {
                    code1 = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPassList.getWidth(), new ArrayList<String>(Arrays.asList("是","否")), ivPassArrow, (ty, i) -> {
                        tvPassype.setText(ty);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivPassArrow);
                code1.showAsDropDown(flPassList, 0, 0);
            }
        });

        flYaoqiuList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (code2 != null) {
                    if (code2.isShowing()) {
                        code2.dismiss();
                    }
                } else {
                    code2 = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flYaoqiuList.getWidth(), new ArrayList<String>(Arrays.asList("是","否")), ivYaoqiuArrow, (ty, i) -> {
                        tvYaoqiuType.setText(ty);
                        if("是".equals(ty)){
                            isPass.setVisibility(View.GONE);
                            tvPassype.setText(null);
                        }else{
                            isPass.setVisibility(View.VISIBLE);
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivYaoqiuArrow);
                code2.showAsDropDown(flYaoqiuList, 0, 0);
            }
        });

    }

    private void initInfoView(WoPartWobomline woPartWobomline){
        etCust.setText(woPartWobomline.getWORKORDER().getCUSTOMERCODE());
        etMMT.setText(woPartWobomline.getWORKORDER().getUDF().getMainMatType());
        etproductModuct.setText(woPartWobomline.getPART().getSPEC2());
        // 芯片型号，存在多芯情况
        String wafers = "";
        for(WoPartWobomline.XWorkOrderBomLine item :woPartWobomline.getWORKORDERBOMLINELIST()){
            if(item.getMaterialName().startsWith("15001")){
                wafers+=item.getMATERIALDESC()+",";
            }
        }
        etWaferId.setText(wafers.substring(0,wafers.length()-1));

        // 带出工单所有货源号
       List<WoPartWobomline.XWorkOrderSource> wipWoSources =  woPartWobomline.getWIPWOSOURCE();

       if(wipWoSources.size() > 0){
           for(WoPartWobomline.XWorkOrderSource item : wipWoSources){
//               hyhList.add(item.getReserved3());
               allhyhList.add(item.getReserved3());
           }
       }

       // 显示的货源号 all全部 - haveDate已经录入
        hyhList.addAll(allhyhList);
        List<WoPartWobomline.BreWaferHDOnTest> wipWoHaves = woPartWobomline.getWIPWOHAVEDATA();
       if(wipWoHaves.size() > 0){
           for(WoPartWobomline.BreWaferHDOnTest item : wipWoHaves){
               haveDatahyhList.add(item.getEthyh());
           }
           hyhList.removeAll(haveDatahyhList);
       }else{
           hyhList.addAll(allhyhList);
       }

    }

    @Override
    protected void initData() {

    }

    @OnClick({ R.id.tvBaseSubmit,R.id.ivBCOPArrow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                submit();
                break;
            case R.id.ivBCOPArrow:
                if (hyhList.size() <= 0){
                    showToast("未获取到货源号!",false);
                    return;
                }
                // 去重
                Set<String> set = new HashSet<>(hyhList);
                hyhList.clear();
                hyhList.addAll(set);

                codePopHyh = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flBCOPList.getWidth(), hyhList, ivBCOPArrow, (codeS, i) -> {
                    ethyh.setText(codeS);
                    if(StringUtils.isNotEmpty(codeS)){
                        List<WoPartWobomline.XWorkOrderSource> temps =  woPartWobomline.getWIPWOSOURCE();
                        List<WoPartWobomline.XWorkOrderSource> temps2 = new ArrayList<>(); // 同货源号的
                        if(temps.size() > 0){

                            for(WoPartWobomline.XWorkOrderSource item : temps){
                                if(item.getReserved3().equals(codeS)){
                                    temps2.add(item);
                                }
                            }

                            WoPartWobomline.XWorkOrderSource min = temps2.get(0);
                            if(temps2.size() > 0){  // 同货源号的
                                for(WoPartWobomline.XWorkOrderSource temp : temps2){
                                   if( Integer.parseInt(temp.getReserved5()) < Integer.parseInt(min.getReserved5())){
                                       min = temp;
                                   }
                                }

                                etWaferLot.setText(min.getSourceMlotId());
                            }
                        }
                    }
                });
                FreeApi_PopUtils.setArrowShow(ivBCOPArrow);
                codePopHyh.showAsDropDown(flBCOPList, 0, 0);
                break;
        }
    }

    private void submit(){

        if(getText(etEqpId).equals("") || getText(etWaferId).equals("") || ethyh.getText().equals("") || getText(etWaferLot).equals("") || getText(etWaferhd).equals("") ){
            showToast("必须信息不能为空", false);
            return;
        }

        // 是否符合要求
        if(StringUtils.isEmpty(tvYaoqiuType.getText())){
            showToast("必须选择是否符合要求", false);
            return;
        }

        // 不符合要求，必选是否放行
        if(tvYaoqiuType.getText().equals("否") && StringUtils.isEmpty(tvPassype.getText())){
            showToast("不符合要求，必选是否放行", false);
            return;
        }

            // 整数或小数 = 芯片厚度
            String regex = "^\\d+(\\.\\d+)?|\\.\\d+$";
            boolean b = Pattern.matches(regex,getText(etWaferhd));
            if(!b){
                showToast("芯片厚度必须是整数或小数!", false);
                return;
            }


        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    clearAllInfo();
                    showToast("成功", true);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "WORDER_QUERY_INFOS");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTION", "SAVE_WAFER_HD");
        map.addProperty("WORDER", getText(etEqpId));
        map.addProperty("CUSTOMERCODE", getText(etCust));
        map.addProperty("MAINMATTYPE", getText(etMMT));
        map.addProperty("SPEC2", getText(etproductModuct));
        map.addProperty("etWaferId", getText(etWaferId));
        map.addProperty("ethyh", ethyh.getText().toString());
        map.addProperty("etWaferLot", getText(etWaferLot));
        map.addProperty("etWaferhd", getText(etWaferhd));
        map.addProperty("isOk", tvYaoqiuType.getText().toString());
        if (tvYaoqiuType.getText().equals("是")){
            map.addProperty("isPass", "");
        }else{
            map.addProperty("isPass", (String) tvPassype.getText());
        }
        map.addProperty("etBeiZu",getText(etBeiZu));

        NetUtils.requestPostNet("IF.WORDER_QUERY_INFOS", "Common", BreYFCWaferHDActivity.this, map, callBack);
    }

    public void clearAllInfo(){
        etEqpId.setText(null);
        etCust.setText(null);
        etMMT.setText(null);
        etproductModuct.setText(null);
        etWaferId.setText(null);
        ethyh.setText(null);
        etWaferLot.setText(null);
        etWaferhd.setText(null);
        tvYaoqiuType.setText(null);
//        btn_pass.setChecked(false);
//        btn_ng.setChecked(false);

        tvPassype.setText(null);

        etBeiZu.setText(null);
        etEqpId.requestFocus();
    }
}